/*
   Copyright 2010 the original author or authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package com.googlecode.flightreports.countrysummary;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement; 
import java.sql.SQLException;
import java.text.SimpleDateFormat;

import com.googlecode.flightreports.citydetails.CityDetailsReport;
import com.googlecode.kohmori.reportgen.AbstractSQLSource;
import com.googlecode.kohmori.springmvc.DefaultReportParams;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;

import org.xml.sax.InputSource;

/* 
 * This class creates the report object and uses SQL to populate its values.
 */
public class ReportSQL extends AbstractSQLSource { 

   @Override
   public String getJAXBPackageList() {
      return "com.googlecode.flightreports.countrysummary";
   }

   /**
     * Creates a report object
     * @param dbConn Connection object to run SQL
     * @return report instance, null if no report found
     */
    @SuppressWarnings("restriction")
   public JAXBElement<?> createReportObject(Connection dbConn, DefaultReportParams reportParams) 
    throws SQLException {
        CountrySummaryReport rpt = new CountrySummaryReport();

        SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");
        
        try {
            Calendar cal = new GregorianCalendar();
            rpt.setRunDate(cal.getTime());
            String currentCountry = "XXX";
            Countries.Country currCountryObj = null;
          
            String sqlStatement =
                "SELECT country_name, region, country_iso_code, " +
                " city_name, airport, language," +
                " arrival_count, departure_count " +
                " from APP.V_COUNTRY_SUMMARY " +
                " order by region, country_name, city_name ";
                    
            System.out.println(sqlStatement);
            PreparedStatement pstmt = dbConn.prepareStatement(sqlStatement);
            ResultSet rs = pstmt.executeQuery();

            Countries countries = new Countries();
            rpt.setCountries(countries);  
            
            
            while (rs.next()) {
                if (!currentCountry.equals(rs.getString("country_name"))) {
                    // create a new country object
                    currentCountry = rs.getString("country_name");
                    Countries.Country country = new Countries.Country();
                    country.setCities(new Cities());
                    currCountryObj = country;
                    country.setName(currentCountry);
                    country.setRegion(rs.getString("region"));
                    country.setIsoCode(rs.getString("country_iso_code"));
                    Cities.City city = new Cities.City();
                    city.setName(rs.getString("city_name"));
                    city.setAirport(rs.getString("airport"));
                    city.setLanguage(rs.getString("language"));
                    city.setArrivalCount(rs.getInt("arrival_count"));
                    city.setDepartureCount(rs.getInt("departure_count"));
                    country.getCities().getCity().add(city);
                    rpt.getCountries().getCountry().add(country);
                } else {
                    // add a new city object to present country object
                    Cities.City city = new Cities.City();
                    city.setName(rs.getString("city_name"));
                    city.setAirport(rs.getString("airport"));
                    city.setLanguage(rs.getString("language"));
                    city.setArrivalCount(rs.getInt("arrival_count"));
                    city.setDepartureCount(rs.getInt("departure_count"));
                    currCountryObj.getCities().getCity().add(city);
                }
            }

            pstmt.close();

        } catch (SQLException e) {
            throw new SQLException("Exception in ReportSQL: " + e.getMessage());
        }
        JAXBElement<CountrySummaryReport> jaxbElement = new JAXBElement<CountrySummaryReport>(
              new QName("http://flightreports.googlecode.com/countrysummary","CountrySummaryReport"), 
              CountrySummaryReport.class, rpt); 
        
        return jaxbElement;
    }
}
